package com.ruoyi.lvlian.service.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.DriverVehicleRef;
import com.ruoyi.lvlian.domain.InvoiceDetails;
import com.ruoyi.lvlian.dto.VehicleInfoDto;
import com.ruoyi.lvlian.util.ExcelUtil;
import com.ruoyi.lvlian.vo.VehicleInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.lvlian.mapper.VehicleInfoMapper;
import com.ruoyi.lvlian.domain.VehicleInfo;
import com.ruoyi.lvlian.service.IVehicleInfoService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 车辆信息Service业务层处理
 *
 * @author liyuxi
 * @date 2024-06-06
 */
@Service
public class VehicleInfoServiceImpl implements IVehicleInfoService {
    @Autowired
    private VehicleInfoMapper vehicleInfoMapper;

    /**
     * 查询车辆信息
     *
     * @param id 车辆信息主键
     * @return 车辆信息
     */
    @Override
    public VehicleInfo selectVehicleInfoById(String id) {
        VehicleInfo vehicleInfo = vehicleInfoMapper.selectVehicleInfoById(id);
        if(null ==vehicleInfo){
            return  null;
        }

        if(StringUtils.isEmpty(vehicleInfo.getDrivingLicenseImg() )){
            vehicleInfoMapper.updateImg( vehicleInfo.getPlateNo(),"driving_license_img"  );
        }
        return vehicleInfo;
    }

    /**
     * 查询车辆信息列表
     *
     * @param vehicleInfo 车辆信息
     * @return 车辆信息
     */
    @Override
    public List<VehicleInfoVo> selectVehicleInfoList(VehicleInfoDto vehicleInfo) {
        List<VehicleInfoVo> vehicleInfoVos = vehicleInfoMapper.selectVehicleInfoList(vehicleInfo);
        for (VehicleInfoVo vo : vehicleInfoVos) {
            String driverName ="";
            if(StringUtils.isNotEmpty( vo.getPhone() )){
                driverName =   vehicleInfoMapper.queryRecentDriverByPhone(vo.getPhone()) ;
            }else {
                 driverName = vehicleInfoMapper.queryRecentDriver(vo.getPlateNo() );
            }


            vo.setDriverName(driverName);
        }
        return vehicleInfoVos;
    }

    /**
     * 新增车辆信息
     *
     * @param vehicleInfo 车辆信息
     * @return 结果
     */
    @Override
    public int insertVehicleInfo(VehicleInfo vehicleInfo) {

        if( StringUtils.isEmpty( vehicleInfo.getPhone() ) ){
            vehicleInfo.setId(    MD5Utils.md5(vehicleInfo.getPlateNo()+ vehicleInfo.getDataSource()  + vehicleInfo.getOrgCode() )   );
        }else{
            vehicleInfo.setId(    MD5Utils.md5(vehicleInfo.getPlateNo()+vehicleInfo.getPhone()+ vehicleInfo.getDataSource()  + vehicleInfo.getOrgCode() )   );
        }
        vehicleInfo.setCreateUser(SecurityUtils.getUsername());
        vehicleInfo.setCreateDate(DateUtils.getCurrentTime());
        if(StringUtils.isEmpty( vehicleInfo.getDataSource() ) ){
            vehicleInfo.setDataSource("实时物流小程序");
        }
        if(StringUtils.isEmpty( vehicleInfo.getCreateUser() ) ){
            vehicleInfo.setCreateUser( vehicleInfo.getPhone());
        }
        vehicleInfo.setViewFlag(true);
        return vehicleInfoMapper.insertVehicleInfo(vehicleInfo);
    }

    /**
     * 修改车辆信息
     *
     * @param vehicleInfo 车辆信息
     * @return 结果
     */
    @Override
    public int updateVehicleInfo(VehicleInfo vehicleInfo) {

        vehicleInfo.setPlateNo(vehicleInfo.getPlateNo().toUpperCase() );
        int updateResult = 0;
        if (StringUtils.isEmpty(vehicleInfo.getId())) {
            updateResult = this.insertVehicleInfo(vehicleInfo);
        } else {
            updateResult = vehicleInfoMapper.updateVehicleInfo(vehicleInfo);
        }

        if (0 == updateResult) {
            updateResult = this.insertVehicleInfo(vehicleInfo);
        }


        if (StringUtils.isNotEmpty(vehicleInfo.getLicenseNo())) {
            List<DriverVehicleRef> list = new ArrayList<>();
//        调整公司 ，一个用户存在多个公司
            DriverVehicleRef ref = new DriverVehicleRef();
            ref.setPhone(vehicleInfo.getPhone());
            ref.setPlateNo(vehicleInfo.getPlateNo());
            ref.setLicenseNo(vehicleInfo.getLicenseNo());
            ref.setId(MD5Utils.md5(ref.getLicenseNo() + ref.getPlateNo()));
            ref.setCreateDate(DateUtils.getCurrentTime());
            list.add(ref);
            vehicleInfoMapper.saveBatchDriverVehicleRef(list);
        }


        return updateResult;

    }

    /**
     * 批量删除车辆信息
     *
     * @param ids 需要删除的车辆信息主键
     * @return 结果
     */
    @Override
    public int deleteVehicleInfoByIds(String[] ids) {
        return vehicleInfoMapper.deleteVehicleInfoByIds(ids);
    }

    /**
     * 删除车辆信息信息
     *
     * @param id 车辆信息主键
     * @return 结果
     */
    @Override
    public int deleteVehicleInfoById(String id) {
        return vehicleInfoMapper.deleteVehicleInfoById(id);
    }

    @Override
    public int queryVehicleCountByDriverPhone(String driverPhone) {
        return vehicleInfoMapper.deleteVehicleInfoById(driverPhone);
    }

    @Override
    public List<VehicleInfo> queryVehicleListByDriverPhoneOrId(String driverPhoneOrId) {
        List<VehicleInfo> vehicleInfos1 = vehicleInfoMapper.queryVehicleListByDriverByPhone( driverPhoneOrId);
        List<VehicleInfo> vehicleInfos2 = vehicleInfoMapper.queryVehicleListByDriverByLicenseNo( driverPhoneOrId);

// 处理空值
        vehicleInfos1 = vehicleInfos1 != null ? vehicleInfos1 : new ArrayList<>();
        vehicleInfos2 = vehicleInfos2 != null ? vehicleInfos2 : new ArrayList<>();

// 简单合并（不去重）
        List<VehicleInfo> mergedList = new ArrayList<>();
        mergedList.addAll(vehicleInfos1);
        mergedList.addAll(vehicleInfos2);

// 如果需要去重
        List<VehicleInfo> vehicleInfos = mergedList.stream()
                .filter(Objects::nonNull)
                .filter(vehicle -> vehicle.getId() != null)
                .collect(Collectors.collectingAndThen(
                        Collectors.toMap(
                                VehicleInfo::getId,
                                Function.identity(),
                                (existing, replacement) -> existing, // 如果ID重复，保留已有的
                                LinkedHashMap::new
                        ),
                        map -> new ArrayList<>(map.values())
                ));


        return  vehicleInfos;
    }

    @Override
    public List<VehicleInfo> importInfo(MultipartFile file, String sheetName, int rowNum) throws Exception {
        byte[] fileBytes = file.getBytes();
        List<VehicleInfo> invoiceRecyclingInfos = ExcelUtil.readExcel(fileBytes, VehicleInfo.class, sheetName, rowNum);
        return invoiceRecyclingInfos;
    }

    @Override
    public int bachSave(List<VehicleInfo> dtoList) {
        int saveBatch = 0;

        List<VehicleInfo> newList=new ArrayList<>();
        if (!dtoList.isEmpty()) {
            for (VehicleInfo po : dtoList) {
                if (StringUtils.isNotEmpty(po.getPlateNo()) && StringUtils.isNotEmpty(po.getVehicleOwner())) {
                    po.setPlateNo(po.getPlateNo().toUpperCase() );

                    po.setDataSource("四流平台");
                    po.setCreateUser(SecurityUtils.getUsername());
                    po.setCreateDate(DateUtils.getCurrentTime());
                    if( StringUtils.isEmpty( po.getPhone() ) ){
                        po.setId(    MD5Utils.md5(po.getPlateNo()+ po.getDataSource()  + po.getOrgCode() )   );
                    }else{
                        po.setId(    MD5Utils.md5(po.getPlateNo()+po.getPhone()+ po.getDataSource()  + po.getOrgCode() )   );
                    }

                    po.setViewFlag(true);
                    newList.add(po );
                }
            }

            String[] plateNoList = newList.stream()
                    .map(VehicleInfo::getPlateNo) // 提取出 invoiceNum
                    .distinct()                        // 去重
                    .toArray(String[]::new);

//             导入之前 先删除
//            vehicleInfoMapper.batchDelete(plateNoList);
            saveBatch = vehicleInfoMapper.batchSave(newList);

        }
        return saveBatch;
    }

    @Override
    public List<VehicleInfo> queryVehicleListByDriverPhoneOrIdEffective(String driverPhoneOrId) {
        List<VehicleInfo> vehicleInfos2 = vehicleInfoMapper.queryVehicleListByDriverPhoneOrIdEffective( driverPhoneOrId);
        return  vehicleInfos2;
    }
}
